import { constantRouterMap } from '@/router'

console.log(constantRouterMap, 'permission')
/**
 * @param route
 * @param constantRouterMap
 */
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        const { roles } = data
        let accessedRouters = constantRouterMap
        if (roles.indexOf('admin') >= 0) {
          accessedRouters = constantRouterMap
          console.log(accessedRouters, 'accessedRouters')
        } else {
          accessedRouters = filterAsyncRouter(constantRouterMap)
        }
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }
  }
}
console.log(constantRouterMap, 'permission')

export default permission
